<template>
  <div class="all-courses-page">
    <NavBar />
    
    <div class="courses-content">
      <!-- 搜索结果标题或全部课程标题 -->
      <div class="page-header">
        <template v-if="isSearchMode">
          <h1 class="search-title">搜索结果: <span>{{ searchQuery }}</span></h1>
          <div class="search-stats">找到 {{ filteredCourses.length }} 个结果</div>
        </template>
        <h1 v-else class="page-title">全部课程</h1>
      </div>
      
      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="filter-row">
          <span class="filter-label">学科:</span>
          <div class="filter-options">
            <el-radio-group v-model="filters.subject">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button v-for="subject in subjects" :key="subject.value" :label="subject.value">
                {{ subject.label }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
        
        <div class="filter-row">
          <span class="filter-label">难度:</span>
          <div class="filter-options">
            <el-radio-group v-model="filters.level">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button v-for="level in levels" :key="level.value" :label="level.value">
                {{ level.label }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
        
        <div class="filter-row">
          <span class="filter-label">价格:</span>
          <div class="filter-options price-filter">
            <el-radio-group v-model="filters.price">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="free">免费</el-radio-button>
              <el-radio-button label="paid">付费</el-radio-button>
            </el-radio-group>
            
            <div class="price-range" v-if="filters.price === 'paid'">
              <el-input-number 
                v-model="filters.minPrice" 
                :min="0" 
                :max="filters.maxPrice" 
                size="small" 
                placeholder="最低价"
              />
              <span class="price-separator">-</span>
              <el-input-number 
                v-model="filters.maxPrice" 
                :min="filters.minPrice" 
                size="small" 
                placeholder="最高价"
              />
            </div>
          </div>
        </div>
        
        <div class="filter-row">
          <span class="filter-label">排序:</span>
          <div class="filter-options">
            <el-radio-group v-model="filters.sort">
              <el-radio-button label="popular">最热门</el-radio-button>
              <el-radio-button label="newest">最新上线</el-radio-button>
              <el-radio-button label="rating">评分最高</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </div>
      
      <!-- 课程列表 -->
      <div class="courses-grid">
        <template v-if="filteredCourses.length > 0">
          <div 
            v-for="(course, index) in paginatedCourses" 
            :key="index" 
            class="course-card"
            @click="navigateToCourse(course)"
          >
            <div class="course-image" :style="{ backgroundImage: `url(${course.image})` }">
              <div class="course-level" :class="course.level">{{ getLevelText(course.level) }}</div>
              <div class="course-tag" v-if="course.tag">{{ course.tag }}</div>
            </div>
            <div class="course-info">
              <h3 class="course-title">{{ course.title }}</h3>
              <p class="course-description">{{ course.description }}</p>
              <div class="course-meta">
                <div class="course-teacher" v-if="course.teacher">
                  <el-avatar :size="24" :src="course.teacher.avatar"></el-avatar>
                  <span>{{ course.teacher.name }}</span>
                </div>
                <div class="course-stats">
                  <span><el-icon><User /></el-icon> {{ course.students }}</span>
                  <span><el-icon><Star /></el-icon> {{ course.rating }}</span>
                </div>
              </div>
              <div class="course-bottom">
                <div class="course-price" :class="{ free: course.price === '免费' }">
                  {{ course.price }}
                </div>
                <el-button type="primary" size="small">查看详情</el-button>
              </div>
            </div>
          </div>
        </template>
        
        <!-- 无结果提示 -->
        <div v-if="filteredCourses.length === 0" class="no-results">
          <el-empty description="没有找到符合条件的课程" />
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredCourses.length > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalCourses"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <FooterBar />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
import { User, Star } from '@element-plus/icons-vue';
import NavBar from '@/components/common/NavBar.vue';
import FooterBar from '@/components/common/FooterBar.vue';

const router = useRouter();
const route = useRoute();
const store = useStore();

// 判断是否为搜索模式
const searchQuery = computed(() => route.query.q || '');
const isSearchMode = computed(() => !!searchQuery.value);

// 筛选条件
const filters = ref({
  subject: 'all',
  level: 'all',
  price: 'all',
  minPrice: 0,
  maxPrice: 2000,
  sort: 'popular'
});

// 分页
const currentPage = ref(1);
const pageSize = ref(12);

// 学科选项 - 高中9科
const subjects = [
  { value: 'math', label: '数学' },
  { value: 'physics', label: '物理' },
  { value: 'chemistry', label: '化学' },
  { value: 'biology', label: '生物' },
  { value: 'chinese', label: '语文' },
  { value: 'english', label: '英语' },
  { value: 'politics', label: '政治' },
  { value: 'history', label: '历史' },
  { value: 'geography', label: '地理' }
];

// 难度选项
const levels = [
  { value: 'beginner', label: '初级' },
  { value: 'intermediate', label: '中级' },
  { value: 'advanced', label: '高级' }
];

// 从 store 获取课程数据
const allCourses = computed(() => store.state.home.allCourses || []);

// 应用筛选条件
const filteredCourses = computed(() => {
  let result = [...allCourses.value];
  
  // 搜索关键词匹配（仅在搜索模式下）
  if (isSearchMode.value) {
    result = result.filter(course => {
      return course.title.toLowerCase().includes(searchQuery.value.toLowerCase()) || 
             course.description.toLowerCase().includes(searchQuery.value.toLowerCase());
    });
    
    // 记录搜索历史
    if (searchQuery.value) {
      store.dispatch('home/addSearchHistory', searchQuery.value);
    }
  }
  
  // 按学科筛选
  if (filters.value.subject !== 'all') {
    result = result.filter(course => course.subject === filters.value.subject);
  }
  
  // 按难度筛选
  if (filters.value.level !== 'all') {
    result = result.filter(course => course.level === filters.value.level);
  }
  
  // 按价格筛选
  if (filters.value.price !== 'all') {
    if (filters.value.price === 'free') {
      result = result.filter(course => course.price === '免费');
    } else {
      // 付费课程 + 价格范围筛选
      result = result.filter(course => {
        if (course.price === '免费') return false;
        
        // 将价格字符串转换为数字进行比较
        const priceNum = parseFloat(course.price.replace('¥', '').replace(',', ''));
        return priceNum >= filters.value.minPrice && priceNum <= filters.value.maxPrice;
      });
    }
  }
  
  // 排序
  if (filters.value.sort === 'popular') {
    result.sort((a, b) => b.students - a.students);
  } else if (filters.value.sort === 'newest') {
    // 假设有上线时间字段，这里简单按ID排序
    result.sort((a, b) => b.id - a.id);
  } else if (filters.value.sort === 'rating') {
    result.sort((a, b) => b.rating - a.rating);
  }
  
  return result;
});

// 分页后的课程
const paginatedCourses = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredCourses.value.slice(start, end);
});

// 总课程数
const totalCourses = computed(() => filteredCourses.value.length);

// 获取难度文本
const getLevelText = (level) => {
  const levelMap = {
    'beginner': '初级',
    'intermediate': '中级',
    'advanced': '高级'
  };
  return levelMap[level] || '未知';
};

// 页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 导航到课程详情
const navigateToCourse = (course) => {
  router.push(`/course/${course.id}`);
};

// 监听路由变化，重置分页
watch(() => route.query, () => {
  currentPage.value = 1;
}, { deep: true });

onMounted(() => {
  // 可以在这里发送请求获取课程列表
  console.log('加载课程列表');
});
</script>

<style lang="scss" scoped>
.all-courses-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
  
  .courses-content {
    flex: 1;
    width: 1200px;
    margin: 20px auto;
    
    .page-header {
      margin-bottom: 20px;
      
      .page-title {
        margin: 0;
        font-size: 24px;
        color: #303133;
      }
      
      .search-title {
        font-size: 24px;
        color: #303133;
        margin: 0 0 10px;
        
        span {
          color: #1e88e5;
        }
      }
      
      .search-stats {
        color: #606266;
        font-size: 14px;
      }
    }
    
    .filter-section {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      padding: 20px;
      margin-bottom: 20px;
      
      .filter-row {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .filter-label {
          flex: 0 0 60px;
          color: #606266;
        }
        
        .filter-options {
          flex: 1;
          
          &.price-filter {
            display: flex;
            align-items: center;
            
            .price-range {
              display: flex;
              align-items: center;
              margin-left: 20px;
              
              .price-separator {
                margin: 0 10px;
                color: #909399;
              }
            }
          }
        }
      }
    }
    
    .courses-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr); // 每行4条课程
      gap: 20px;
      margin-bottom: 30px;
      
      @media (max-width: 1200px) {
        grid-template-columns: repeat(3, 1fr);
      }
      
      @media (max-width: 992px) {
        grid-template-columns: repeat(2, 1fr);
      }
      
      @media (max-width: 576px) {
        grid-template-columns: 1fr;
      }
      
      .course-card {
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        overflow: hidden;
        transition: transform 0.3s, box-shadow 0.3s;
        cursor: pointer;
        
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        
        .course-image {
          height: 160px;
          background-size: cover;
          background-position: center;
          position: relative;
          
          .course-level {
            position: absolute;
            top: 10px;
            left: 10px;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: #fff;
            
            &.beginner {
              background-color: #67c23a;
            }
            
            &.intermediate {
              background-color: #e6a23c;
            }
            
            &.advanced {
              background-color: #f56c6c;
            }
          }
          
          .course-tag {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: #1e88e5;
            color: #fff;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
          }
        }
        
        .course-info {
          padding: 15px;
          
          .course-title {
            margin: 0 0 10px;
            font-size: 16px;
            color: #303133;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .course-description {
            margin: 0 0 10px;
            color: #606266;
            font-size: 14px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            height: 42px;
          }
          
          .course-meta {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
            
            .course-teacher {
              display: flex;
              align-items: center;
              
              span {
                margin-left: 10px;
                color: #606266;
                font-size: 14px;
              }
            }
            
            .course-stats {
              display: flex;
              
              span {
                display: flex;
                align-items: center;
                margin-left: 15px;
                color: #909399;
                font-size: 14px;
                
                .el-icon {
                  margin-right: 5px;
                }
              }
            }
          }
          
          .course-bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .course-price {
              font-weight: bold;
              color: #f56c6c;
              
              &.free {
                color: #67c23a;
              }
            }
          }
        }
      }
      
      .no-results {
        grid-column: 1 / -1;
        padding: 50px 0;
        text-align: center;
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-bottom: 30px;
    }
  }
}
</style>